package PTOP.ptopJmsTemplate;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;

@Configuration
public class ConfigClass {
    public static String BROKER_URL = "tcp://0.0.0.0:61616";
    public static String USER = "admin";
    public static String PASSWORD = "admin";
    public static String DESITNATION = "SystemA.SystemB.Queue";

    @Bean
    public ConnectionFactory connectionFactory(){
        //连接池创建Factory
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        connectionFactory.setSessionCacheSize(20);
        return  connectionFactory;
    }

    private ActiveMQConnectionFactory activeMQConnectionFactory(){
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
        activeMQConnectionFactory.setBrokerURL(BROKER_URL);
        activeMQConnectionFactory.setUserName(USER);
        activeMQConnectionFactory.setPassword(PASSWORD);
        return activeMQConnectionFactory;
    }

    @Bean
    public Queue mqQueue(){
        return  new ActiveMQQueue(DESITNATION);
    }

    @Bean
    public JmsTemplate mqJmsTemplate(ConnectionFactory factory,Queue queue){
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(factory);
        jmsTemplate.setDefaultDestination(queue);
        jmsTemplate.setReceiveTimeout(5 * 1000);
        return jmsTemplate;
    }

}
